<?php


namespace App\MessageHandler;


use App\Entity\Page;
use App\Entity\PageComment;
use App\Entity\Setting;
use App\Message\PageCommentReply;
use App\Utils\Helper\GetterHelper;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class PageCommentReplyHandler implements MessageHandlerInterface {
    private $logger;
    private $mailer;
    private $container;

    public function __construct (LoggerInterface $logger, MailerInterface $mailer, ContainerInterface $container) {
        $this->logger = $logger;
        $this->mailer = $mailer;
        $this->container = $container;
    }

    public function __invoke (PageCommentReply $pageCommentReply) {
        $page_comment = GetterHelper::getEntityManager()->getRepository(PageComment::class)->find($pageCommentReply->getPageCommentId());
        if (!is_object($page_comment)) {
            $this->logger->error('回复邮件发送失败：未找到回复评论，ID '.$pageCommentReply->getPageCommentId());
            return;
        }
        $page = GetterHelper::getEntityManager()->getRepository(Page::class)->find($page_comment->getPageId());
        if (!is_object($page)) {
            $this->logger->error('回复邮件发送失败：对应文章不存在，ID '.$page_comment->getPageId());
            return;
        }
        $setting = GetterHelper::getEntityManager()->getRepository(Setting::class)->getCurrentSetting();
        if (!$setting->getIsReply()) {
            $this->logger->notice('未开启回复通知功能');
            return;
        }

        if (!$page_comment->getStatus()) {
            $this->logger->warning('回复邮件发送失败：当前评论未审核通过，ID '.$pageCommentReply->getPageCommentId());
            return;
        }
        $parent_comment = $page_comment->getParentComment();
        if (!is_object($parent_comment)) {
            $this->logger->error('回复邮件发送失败，被回复评论不存在，ID '.$page_comment->getParentId());
            return;
        }
        if (!$parent_comment->getEmail()) {
            $this->logger->error('回复邮件发送失败，被回复评论邮箱地址错误 '.$parent_comment->getEmail());
            return;
        }

        $email = (new TemplatedEmail())
            ->from($this->container->getParameter('app.smtp.email'))
            ->to($parent_comment->getEmail())
            ->subject('【'.$setting->getSiteName().'】您有新的回复')
            ->htmlTemplate('backend/public/page_comment_reply.html.twig')
            ->context([
                'page_id'        => $page->getId(),
                'title'          => $page->getTitle(),
                'page_comment'   => $page_comment,
                'parent_comment' => $parent_comment,
            ]);
        $this->mailer->send($email);
    }
}